from typing import TYPE_CHECKING, Dict, Any, Optional
import random
import pygame
from model import Model, GridManager, Player, PlayerManager

from const import (
    EVENT_TRIGGER_INTERVAL,
    TIME_LIMIT_START_EVENT,
)

class EventSystem:
    """
    处理随机事件触发与效果
    """
    def __init__(self):
        self.turn_count = 0
        self.event_probability = 0.5  # 事件触发概率


    def next_turn(self) -> None:
        self.turn_count += 1

    def trigger_event(self, model: 'Model') -> Optional[str]:
        """
        随机触发事件
        """
        grid_manager: GridManager = model.grid_manager
        player_manager: PlayerManager = model.player_manager

        self.turn_count += 1

        # 每回合有概率触发新事件
        if self.turn_count % EVENT_TRIGGER_INTERVAL == 0 and random.random() < self.event_probability:
            event_type = random.choice(["trap", "neutral_piece", "time_limit", "shuffle"])

            # 测试代码
            # event_type = random.choice(["time_limit"])

            if event_type == "trap":
                # 随机选择一个空格子作为陷阱
                empty_cells = []
                for y in range(grid_manager.grid_size):
                    for x in range(grid_manager.grid_size):
                        if grid_manager.grid[y][x] is None and (x, y) not in grid_manager.trapped_cells:
                            empty_cells.append((x, y))
                if empty_cells:
                    trap_position = random.choice(empty_cells)
                    grid_manager.update_trap(trap_position, True)
                    return f"Trap event! Cell {trap_position} is temporarily unavailable"

            elif event_type == "neutral_piece":

                # 如果有中立棋子，则向四周移动位置
                if len(grid_manager.neutral_cells) > 0:
                    # 记录需要移动的目标
                    new_positions = []
                    for pos in grid_manager.neutral_cells:
                        # 随机选择一个方向
                        directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
                        random.shuffle(directions)
                        moved = False
                        for direction in directions:
                            new_pos = (pos[0] + direction[0], pos[1] + direction[1])
                            # 使用model.py中的检查函数
                            if grid_manager.can_move_neutral_to(new_pos):
                                new_positions.append((pos, new_pos))
                                moved = True
                                break
                        if not moved:
                            # 如果没有可移动方向，保持原地
                            new_positions.append((pos, pos))
                    # 执行移动
                    for old_pos, new_pos in new_positions:
                        if old_pos != new_pos:
                            if grid_manager.move_piece(old_pos, new_pos):
                                grid_manager.neutral_cells.remove(old_pos)
                                grid_manager.neutral_cells.append(new_pos)

                # 随机生成一个中立棋子
                empty_cells = grid_manager.get_empty_cells()
                if empty_cells:
                    pos = random.choice(empty_cells)
                    grid_manager.place_neutral_piece(pos)
                    

                # 检查棋盘是否已满，已满的话调用扩展棋盘函数
                if grid_manager.is_full():
                    grid_manager.expand_grid()

                return f"Neutral piece event! A neutral piece has been placed"
                    

            elif event_type == "time_limit":
                # 标记本回合有时间限制
                pygame.event.post(pygame.event.Event(TIME_LIMIT_START_EVENT))
                return "Time-limited round!"

            elif event_type == "shuffle":
                grid_manager.shuffle_board()
                return "The board has been shuffled!"

        return None